package com.vm.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.pay.PayResult;
import com.alipay.sdk.pay.SignUtils;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.LocalUserInfoDao;
import com.vm.model.LocalUserInfo;
import com.vm.model.UserSign;
import com.vm.model.UserSignDetail;
import com.vm.utils.ApkUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月14日 下午5:03:11]
 * @Version: [v1.0]
 * 
 */
public class SignActivity extends Activity {
	// 商户PID
	public static final String PARTNER = "2088712200989071";
	// 商户收款账号
	public static final String SELLER = "zhifubao@weimaikeji.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAN6gZ8XfMYPCN/rGbZCikUpFDGUqX6qG9U1mNtWHejb25hI86+YRxZ51tbDzRjUcZm2KXFCC5nCD2l4+t9QndaWyvCfYhSWl9mIvcVNN8YClE7JwBeUpqLVqE3zwd9gCOaYhjYhO73FgeSv9TrBrQCxf/RFiXJG/e2dTPUHbex7FAgMBAAECgYBOCPPXDBETGjT9Fii5lgJPgjyCCYRXBc9ePgHifwZ71bd3lRsrHfejP6dcSynE3BubMfCB2CBmOBGHD3zoRJybvNUdsXA/7i1aCA9TXGBbDnVxtoLiIt7I/9zu9EiDddevsDhXBZKXHic4QCFZ7H8TZlRyEY1qpSrBx5Mg9WbA0QJBAPJxAfs+FTW25URngtVgQin88dQCFVBb8sh9SQvPwa1HhK1lfki2QhXsgCfabys/7L3DGDTqfasAueRl5rr9fNsCQQDrE7Y3s15f9qYAYAfh2+pKOl3fw4auGG3zrJfRrFMm3R5KNcbqhhIV7HucHI0NnnMxRcgTuyLlH7WnTxTHstTfAkEAic56ldkgLTwc7dj4oVjpwvwoaZ4Vh2v8gMHWN4SMTnaMkBNUyPfwcI3R+tVKw4a+hs7Sf6GadQ0gnRbfJALaaQJAFXqDl6tH4DTFDhu4HKbfTVDv6tYOpDGPOkh2xq2cG1zwu48WUa9WT7J/yM/DA4+KruHVWhgrJAw1qMfM+kIYuQJBAMGsHLMBLjjpbiLw5BML5DPRsGQSWq3Re/Am+VGGTDD8ftovj1/jO4sZVW5QGuPl8s9SVdEo8+KWNtRxLXej7vc=";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;
	protected static final String TAG = "SignActivity";
	LinearLayout rlayout_week;
	Button btn_sign_in;
	Button btn_signed_in;
	private LocalUserInfoDao luidao;
	private LocalUserInfo userInfo;
	private RequestQueue mQueue;
	TextView tv_continuous_days;
	TextView tv_total;
	TextView tv_warning;
	int times = -1;
	UserSign userSign;
	ImageView imgbtn_search_back;
	String sign;
	private HashMap<String, Boolean> signHashMap;

	private List<String> list = new ArrayList<String>();
	private GridView gdDate;
	// private GridView gdWeek;
	private int dayMaxNum;
	private int year, month, day;
	Time t = new Time();
	TextView tv_NowDate;
	String date;
	String stime;
	String intergral;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_in);
		init();
		ifSign();
		getDate();
		sign = getIntent().getStringExtra("sign");
		if (sign != null) {
			intergral = getIntent().getStringExtra("intergral");
			SignSuccessDialog.showDialogForLoading(SignActivity.this, true,
					intergral);
			btn_signed_in.setVisibility(View.VISIBLE);
			btn_sign_in.setVisibility(View.GONE);
		}
	}

	public void ifSign() {
		if (userInfo != null) {
			String url = VMConst.REQUEST_URL + "ifSign?userId="
					+ userInfo.getUserId();
			JsonObjectRequest stringRequest = new JsonObjectRequest(url, null,
					new Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {

							userSign = JsonUtils.jsonToBean(response,
									UserSign.class);
							if (userSign != null) {
								times = userSign.getTimes();
								String today = StringUtil.getDate(4);

								android.util.Log.i(TAG, userSign.getLast());
								android.util.Log.i(TAG, Integer.toString(times));
								android.util.Log.i(TAG,
										Integer.toString(userSign.getTotal()));
								if (!today.equals(userSign.getLast())) {

									btn_sign_in.setVisibility(View.VISIBLE);
									btn_sign_in
											.setOnClickListener(btnClickListener);
								} else {
									btn_sign_in.setVisibility(View.GONE);
									btn_signed_in.setVisibility(View.VISIBLE);
								}
								tv_total.setText(Integer.toString(userSign
										.getTotal()));
							} else {
								times = 0;
								btn_sign_in.setVisibility(View.VISIBLE);
								btn_sign_in
										.setOnClickListener(btnClickListener);
							}
							// tv_continuous_days.setText(Integer.toString(times));
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError arg0) {
							btn_sign_in.setVisibility(View.VISIBLE);
							btn_sign_in.setOnClickListener(btnClickListener);
						}
					});

			mQueue.add(stringRequest);

		} else {
			tv_warning.setVisibility(View.VISIBLE);
			tv_warning.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(SignActivity.this,
							LoginActivity.class);
					startActivity(intent);
				}
			});
			rlayout_week.setVisibility(View.GONE);
		}
	}

	public void getDate() {
		signHashMap = new HashMap<String, Boolean>();
		String url2 = VMConst.REQUEST_URL + "getDetails?userId="
				+ userInfo.getUserId();
		JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url2,
				new Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray response) {
						for (int i = 0; i < response.length(); i++) {
							try {
								JSONObject jsonObject = response
										.getJSONObject(i);
								final UserSignDetail userSignDetail = JsonUtils
										.jsonToBean(jsonObject,
												UserSignDetail.class);

								int day = Integer.parseInt(userSignDetail
										.getStime().substring(8, 10));
								signHashMap.put(Integer.toString(day), true);

								initData();
								tv_continuous_days.setText(Integer
										.toString(response.length()));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				});
		mQueue.add(jsonArrayRequest);
	}

	protected void onResume() {
		ifSign();
		getDate();
		if (userInfo != null) {
			rlayout_week.setVisibility(View.VISIBLE);
			btn_sign_in.setVisibility(View.VISIBLE);
			tv_warning.setVisibility(View.GONE);
		}
		super.onResume();
	}

	/**
	 * 初始化
	 */
	private void init() {
		rlayout_week = (LinearLayout) findViewById(R.id.rlayout_week);
		btn_sign_in = (Button) findViewById(R.id.btn_sign_in);
		btn_signed_in = (Button) findViewById(R.id.btn_signed_in);
		tv_continuous_days = (TextView) findViewById(R.id.tv_continuous_days);
		tv_total = (TextView) findViewById(R.id.tv_total);
		tv_warning = (TextView) findViewById(R.id.tv_warning);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		mQueue = MyVolley.getRequestQueue();
		luidao = new LocalUserInfoDao(this);
		userInfo = luidao.query();
		initCalender();

	}

	public void initCalender() {
		tv_NowDate = (TextView) findViewById(R.id.tv_NowDate);
		t.setToNow();
		year = t.year;
		// year = 2015;
		month = t.month + 1;
		// month = 3;
		day = t.monthDay;
		// day = 25;
		final String date = year + "-" + month + "-" + day;
		tv_NowDate.setText(date);
		// sdao.open();

	}

	@SuppressLint("SimpleDateFormat")
	public void initData() {
		gdDate = (GridView) findViewById(R.id.gv_calender);
		// gdWeek = (GridView) findViewById(R.id.gv_week);
		gdDate.setFocusable(false);
		// gdWeek.setFocusable(false);
		// gdWeek.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// getWeekAdapter myAdapter = new getWeekAdapter();
		// gdWeek.setAdapter(myAdapter);
		// 查询当月已签到的日期
		list.clear();
		dayMaxNum = getDaysByYearMonth(year, month);
		SimpleDateFormat dateFm = new SimpleDateFormat("E");
		// 查出当月1号是周几，从周一开始到周日
		@SuppressWarnings("deprecation")
		String dayofWeek = dateFm.format(new Date(year, month - 1, 1));

		// 从周一开始到周日分别为0,1,2,...
		char dayofweek2 = dayofWeek.toCharArray()[1];
		// Log.i(TAG, dayofweek);
		int spaceNum = 0;
		// 计算日历1号之前的空位数
		switch (dayofweek2) {

		// case '一':
		// spaceNum = 1;
		// break;
		case '二':
			spaceNum = 1;
			break;
		case '三':
			spaceNum = 2;
			break;
		case '四':
			spaceNum = 3;
			break;
		case '五':
			spaceNum = 4;
			break;
		case '六':
			spaceNum = 5;
			break;
		case '日':
			spaceNum = 6;
			break;

		default:
			break;
		}

		for (int i = 0; i < spaceNum; i++) {
			list.add(i, "no");
		}
		dayMaxNum += spaceNum;
		for (int i = spaceNum; i < dayMaxNum; i++) {
			list.add(i, i - spaceNum + 1 + "");
		}
		if (dayMaxNum % 7 != 0) {
			for (int i = dayMaxNum; i < dayMaxNum + (7 - (dayMaxNum % 7)); i++) {
				list.add(i, "no");
			}
		}
		Log.i(TAG, Integer.toString(list.size()));
		gdDate.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gdDate.setAdapter(new getDayNumAdapter(getApplicationContext()));

	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	/*
	 * 点击签到
	 */
	OnClickListener btnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (userInfo != null) {

				String typeName = "签到";
				try {
					typeName = URLEncoder.encode(typeName, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String url = VMConst.REQUEST_URL + "sign?userId="
						+ userInfo.getUserId() + "&stime="
						+ StringUtil.getDate(4) + "&typeName=" + typeName;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String response) {

								if (!response.equals("0")) {
									// tv_continuous_days.setText(Integer
									// .toString(times + 1));
									btn_sign_in.setVisibility(View.GONE);
									btn_signed_in.setVisibility(View.VISIBLE);
									btn_signed_in.setEnabled(false);
									// int addIntergral = 10;
									// if (times / 5 >= 1 && times % 5 == 0) {
									// addIntergral = times / 5 * 15;
									// }
									CurrentUser.INTERGRAL = CurrentUser.INTERGRAL
											+ Integer.parseInt(response);
									int pretotal = Integer.parseInt(tv_total
											.getText().toString());
									tv_total.setText(Integer.toString(Integer
											.parseInt(response) + pretotal));
									luidao.update();
									Intent intent = new Intent(
											SignActivity.this,
											SignActivity.class);
									intent.putExtra("sign", "sign");
									intent.putExtra("intergral", response);
									SignActivity.this.finish();
									startActivity(intent);
								} else {
									Toast toast = Toast.makeText(
											SignActivity.this, "签到失败",
											Toast.LENGTH_SHORT);
									toast.show();
								}
							}
						}, null);

				mQueue.add(stringRequest);

			}
		}
	};

	// class getWeekAdapter extends BaseAdapter {
	// String[] week = new String[] { "日", "一", "二", "三", "四", "五", "六" };
	//
	// @Override
	// public int getCount() {
	// // TODO Auto-generated method stub
	// return week.length;
	// }
	//
	// @Override
	// public Object getItem(int position) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// @Override
	// public long getItemId(int position) {
	// // TODO Auto-generated method stub
	// return position;
	// }
	//
	// @Override
	// public View getView(int position, View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// if (convertView == null) {
	// // 根据布局文件获取View返回值
	// convertView = LayoutInflater.from(getApplicationContext())
	// .inflate(R.layout.sign_in_weekitem, null);
	// }
	// TextView tv_week = (TextView) convertView
	// .findViewById(R.id.tv_week);
	// tv_week.setText(week[position]);
	// return convertView;
	// }
	//
	// }

	class getDayNumAdapter extends BaseAdapter {
		Context c;

		public getDayNumAdapter(Context c) {
			this.c = c;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("ViewHolder")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = LinearLayout.inflate(c, R.layout.sign_in_item, null);
			// TextView txtWeek = (TextView) v.findViewById(R.id.tv_week);
			final TextView txtDay = (TextView) v.findViewById(R.id.tv_date);
			final Button btn_sign_supplement = (Button) v
					.findViewById(R.id.btn_sign_supplement);
			// Button btn_signed = (Button) v.findViewById(R.id.btn_signed);

			// switch (position) {
			// case 0:
			// txtWeek.setText("日");
			// break;
			// case 1:
			// txtWeek.setText("一");
			// break;
			// case 2:
			// txtWeek.setText("二");
			// break;
			// case 3:
			// txtWeek.setText("三");
			// break;
			// case 4:
			// txtWeek.setText("四");
			// break;
			// case 5:
			// txtWeek.setText("五");
			// break;
			// case 6:
			// txtWeek.setText("六");
			// break;
			// }
			//
			// if (position < 7) {
			// txtWeek.setVisibility(View.VISIBLE);
			// }

			if (list.get(position).equals("no")) {
				txtDay.setText("");
				btn_sign_supplement.setVisibility(View.GONE);
			} else {
				int lstDay = Integer.parseInt(list.get(position));

				// 标记当前日期
				if (day == lstDay) {
					txtDay.setText(list.get(position).toString());
					txtDay.setTextColor(Color.RED);
				} else
					txtDay.setText(list.get(position).toString());
				if (day < lstDay) {
					btn_sign_supplement.setVisibility(View.VISIBLE);
				}
				if (signHashMap.containsKey(Integer.toString(lstDay))) {
					btn_sign_supplement
							.setBackgroundResource(R.drawable.signed_in);
					// btn_signed.setVisibility(View.VISIBLE);
				} else if (day > lstDay) {
					btn_sign_supplement.setBackgroundColor(Color
							.parseColor("#ff9131"));
					btn_sign_supplement.setText("补签");
					btn_sign_supplement.setTextColor(Color.WHITE);
					btn_sign_supplement.setTextSize(TypedValue.COMPLEX_UNIT_SP,
							15);
				}
			}
			btn_sign_supplement.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (btn_sign_supplement.getText().toString().equals("补签")) {
						date = txtDay.getText().toString();
						if (ApkUtils.isAppInstalled("com.eg.android.AlipayGphone",
								SignActivity.this)) {
							double money = 0.01;
							// 当需要支付的金额大于0,弹出支付
							check(v);
							pay(money);
						} else {
							Toast toast = Toast.makeText(SignActivity.this,
									"请先下载支付宝钱包", Toast.LENGTH_SHORT);
							toast.show();
							Intent intent = new Intent(SignActivity.this,
									DetailActivity.class);
							intent.putExtra("softId",
									"5b1bffb4-abd5-4cc0-b142-40078ca10814");
							startActivity(intent);
						}
					}
				}
			});
			return v;
		}

	}

	// // 获取当月的天数
	// public static int getCurrentMonthDay() {
	// Calendar a = Calendar.getInstance();
	// a.set(Calendar.DATE, 1);
	// a.roll(Calendar.DATE, -1);
	// int maxDate = a.get(Calendar.DATE);
	// return maxDate;
	// }

	/**
	 * 根据年 月 获取对应的月份 天数
	 * */
	public static int getDaysByYearMonth(int year, int month) {

		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month - 1);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	public static void main(String[] args) {
		// SimpleDateFormat dateFm = new SimpleDateFormat("E");
		// // 查出当月1号是周几，从周一开始到周日
		// String dayofWeek = dateFm.format(new Date(year, month - 1, 1));
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(SignActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					// btn_confirm.setEnabled(true);
					Retroactive();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(SignActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(SignActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
						// btn_confirm.setEnabled(true);
					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(SignActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	public void pay(Double money) {
		// 订单
		String name = "补签";
		String orderInfo = getOrderInfo(name, name, Double.toString(money));

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(SignActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	// 判断是否安装了支付宝

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(SignActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@SuppressLint("SimpleDateFormat")
	private void Retroactive() {
		if (userInfo != null) {

			String typeName = "补签";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			String date1 = sdf.format(new java.util.Date());
			if (Integer.parseInt(date) < 10) {
				stime = date1 + "-0" + date;
			} else {
				stime = date1 + "-" + date;
			}
			try {
				typeName = URLEncoder.encode(typeName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String url = VMConst.REQUEST_URL + "sign?userId="
					+ userInfo.getUserId() + "&stime=" + stime + "&typeName="
					+ typeName;
			StringRequest stringRequest = new StringRequest(url,
					new Listener<String>() {
						@Override
						public void onResponse(String response) {

							if (!response.equals("0")) {
								CurrentUser.INTERGRAL = CurrentUser.INTERGRAL
										+ Integer.parseInt(response);
								int pretotal = Integer.parseInt(tv_total
										.getText().toString());
								tv_total.setText(Integer.toString(Integer
										.parseInt(response) + pretotal));
								luidao.update();
								Intent intent = new Intent(SignActivity.this,
										SignActivity.class);
								intent.putExtra("sign", "sign");
								intent.putExtra("intergral", response);
								SignActivity.this.finish();
								startActivity(intent);
							} else {
								Toast toast = Toast.makeText(SignActivity.this,
										"签到失败", Toast.LENGTH_SHORT);
								toast.show();
							}
						}
					}, null);

			mQueue.add(stringRequest);

		}
	}
}
